package com.lk.web;

import com.lk.pojo.User;
import com.lk.service.UserService;
import com.lk.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    private UserService service = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = service.login(username, password);

        if(user!=null){
            //登录成功

            //是否勾选记住我复选框
            String remember = request.getParameter("remember");
            if("1".equals(remember)){
                //创建cookie对象
                Cookie c_username=new Cookie("username",username);
                Cookie c_password=new Cookie("password",password);
                //设置cookie存活时间
                c_username.setMaxAge(60*60*24);
                c_password.setMaxAge(60*60*24);
                //发送cookie
                response.addCookie(c_username);
                response.addCookie(c_password);
            }

            //将登陆后的user对象存到session
            HttpSession session = request.getSession();
            session.setAttribute("user",user);

            String contextPath = request.getContextPath();
            response.sendRedirect(contextPath+"/brand.html");

        }else {
            //登录失败
            request.setAttribute("login_msg","账号或密码错误");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request,response);
    }
}
